const defaultTagRE = /\{\{((?:.|\r?\n)+?)\}\}/g
export function generate(el) {
  // const children = el.children;
  let children = genChildren(el);
  // 标签-属性-内容
  let code = `_c("${el.tag}", ${el.attrs.length ? genProps(el.attrs) : 'undefined'}${children ? "," + children : ""})`;
  return code;
}

function gen(node) {
  if (node.type == 1) {
    // 元素标签
    return generate(node);
  } else {
    let text = node.text;  // 针对{{name}}怎么处理的呢？
    // 举例： a {{name}} b {{age}}
    // 处理结果： "a" + _s(name) + "b" + _s(age)
    // 不是用match， 而是使用exec
    // lastindex存在问题， 所以先将它置为空
    let tokens = [], match = undefined, index = undefined;
    let lastIndex = defaultTagRE.lastIndex = 0;
    while (match = defaultTagRE.exec(text)) {
      index = match.index;
      if (index > lastIndex) {
        tokens.push(JSON.stringify(text.slice(lastIndex, index)));
      }
      tokens.push(`_s(${match[1].trim()})`);
      lastIndex = index + match[0].length;
    }

    if (lastIndex < text.length) {
      tokens.push(JSON.stringify(text.slice(lastIndex)))
    }


    return `_v(${tokens.join("+")})`;
  }
}

function genChildren(el) {
  let str = "", children = el.children;
  if (children && children.length > 0) {
    return `${children.map(c => gen(c)).join(",")}`
  } else {
    return false;
  }
  // console.log(el);
  // return str;
}

function genProps(attrs) { // 处理属性， 拼接成属性的字符串
  let str = "";
  for (let i = 0; i < attrs.length; i++) {
    let attr = attrs[i];
    if (attr.name === "style") {
      // style = "color: red;" ==>  {style: {color: "red"}}
      let obj = {};
      // 处理数组中无空的
      attr.value.split(";").filter(item => item).forEach(item => {
        let [key, value] = item.split(":");

        obj[key] = value ? value.trim() : "";
      })
      attr.value = obj
    };
    str += `${attr.name}:${JSON.stringify(attr.value)},`
  }
  return `{${str.slice(0, -1)}}`;
}